<template>
    <div class="login-page">
        <div class="glass-card">
            <div class="brand">
                <div class="logo-circle">W</div>
                <div class="title-group">
                    <h1>仓储管理系统</h1>
                    <p>Warehouse Management System</p>
                </div>
            </div>
            <form class="form" @submit.prevent="onSubmit">
                <div class="field">
                    <label>用户名</label>
                    <div class="input-wrap">
                        <span class="prefix">👤</span>
                        <input v-model.trim="username" type="text" placeholder="请输入用户名" autocomplete="username"
                            :disabled="isSubmitting" />
                    </div>
                </div>

                <div class="field">
                    <label>密码</label>
                    <div class="input-wrap">
                        <span class="prefix">🔒</span>
                        <input v-model.trim="password" :type="showPassword ? 'text' : 'password'"
                            placeholder="请输入密码（至少6位）" autocomplete="current-password" :disabled="isSubmitting" />
                        <button type="button" class="suffix-btn" @click="showPassword = !showPassword"
                            :aria-label="showPassword ? '隐藏密码' : '显示密码'">{{ showPassword ? '🙈' : '👁️' }}</button>
                    </div>
                </div>

                <div class="field">
                    <label>验证码</label>
                    <div class="captcha-row">
                        <div class="input-wrap">
                            <span class="prefix">✅</span>
                            <input v-model.trim="captchaInput" type="text" placeholder="输入右侧验证码" maxlength="4"
                                :disabled="isSubmitting" />
                        </div>
                        <button type="button" class="captcha" @click="refreshCaptcha" :disabled="isSubmitting"
                            title="点击刷新验证码">
                            <canvas ref="captchaCanvas" width="96" height="36"></canvas>
                        </button>
                    </div>
                </div>

                <div class="field" style="margin-top:-6px;">
                    <label style="visibility:hidden">&nbsp;</label>
                    <label class="remember">
                        <input type="checkbox" v-model="rememberMe" :disabled="isSubmitting" /> 记住账号密码
                    </label>
                </div>

                <p v-if="errorMessage" class="error">{{ errorMessage }}</p>

                <button class="submit" type="submit" :disabled="!isFormValid || isSubmitting">
                    {{ isSubmitting ? '登录中…' : '登 录' }}
                </button>
            </form>
            <div class="footer-note">© {{ new Date().getFullYear() }} Management WMS</div>
        </div>
        <div class="bg-ornament bg-1"></div>
        <div class="bg-ornament bg-2"></div>
    </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const username = ref('')
const password = ref('')
const captchaInput = ref('')
const generatedCaptcha = ref('')
const captchaCanvas = ref<HTMLCanvasElement | null>(null)
const isSubmitting = ref(false)
const showPassword = ref(false)
const errorMessage = ref('')
const rememberMe = ref<boolean>(localStorage.getItem('rememberMe') === '1')

import myaxios from "../http/MyAxios";

const isFormValid = computed(() => {
    return (
        username.value.trim().length > 0 &&
        password.value.trim().length >= 6 &&
        captchaInput.value.trim().length > 0
    )
})

function randomChar() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    return chars[Math.floor(Math.random() * chars.length)]
}

function generateCaptchaString(len = 4) {
    let s = ''
    for (let i = 0; i < len; i++) s += randomChar()
    return s
}

function drawCaptcha() {
    const canvas = captchaCanvas.value
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const width = canvas.width
    const height = canvas.height

    // background
    ctx.clearRect(0, 0, width, height)
    ctx.fillStyle = '#f3f6fb'
    ctx.fillRect(0, 0, width, height)

    // noise lines
    for (let i = 0; i < 4; i++) {
        ctx.strokeStyle = `rgba(${100 + Math.random() * 100}, ${100 + Math.random() * 100}, ${100 + Math.random() * 100}, 0.6)`
        ctx.beginPath()
        ctx.moveTo(Math.random() * width, Math.random() * height)
        ctx.lineTo(Math.random() * width, Math.random() * height)
        ctx.stroke()
    }

    // dots
    for (let i = 0; i < 40; i++) {
        ctx.fillStyle = `rgba(${50 + Math.random() * 150}, ${50 + Math.random() * 150}, ${50 + Math.random() * 150}, 0.6)`
        ctx.beginPath()
        ctx.arc(Math.random() * width, Math.random() * height, Math.random() * 1.5 + 0.5, 0, Math.PI * 2)
        ctx.fill()
    }

    // text
    const text = generatedCaptcha.value
    const letterSpace = width / (text.length + 1)
    for (let i = 0; i < text.length; i++) {
        const char = text.charAt(i)
        const fontSize = 22 + Math.floor(Math.random() * 6)
        const angle = (Math.random() - 0.5) * 0.6
        ctx.save()
        ctx.font = `${fontSize}px ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial` as string
        ctx.fillStyle = '#2b3a67'
        ctx.translate(letterSpace * (i + 1), height / 2 + 6)
        ctx.rotate(angle)
        ctx.fillText(char, -6, 0)
        ctx.restore()
    }
}
function refreshCaptcha() {
    generatedCaptcha.value = generateCaptchaString(4)
    drawCaptcha()
}

onMounted(() => {
    refreshCaptcha()
    // 预填记住的账号密码
    if (rememberMe.value) {
        const ru = localStorage.getItem('rememberUsername') || ''
        const rp = localStorage.getItem('rememberPassword') || ''
        if (ru) username.value = ru
        if (rp) password.value = rp
    }
})

const userinfo = reactive({
    userAccount: "",
    userPassword: "",
})

async function onSubmit() {
    userinfo.userAccount = username.value;
    userinfo.userPassword = password.value;
    errorMessage.value = ''
    if (!isFormValid.value) {
        errorMessage.value = '请完整填写信息，密码至少6位'
        return
    }
    if (captchaInput.value.trim().toUpperCase() !== generatedCaptcha.value.toUpperCase()) {
        errorMessage.value = '验证码错误'
        refreshCaptcha()
        captchaInput.value = ''
        return
    }

    try {
        isSubmitting.value = true
        // TODO: 替换为真实登录接口调用

        // 模拟登录成功后跳转首页
        myaxios({
            url: "/api/Login/LoginUser",
            method: "post",
            data: userinfo
        })
            .then(res => {
                console.log(userinfo);

                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    // 正确保存后端返回的 JWT 到本地，并设置默认请求头
                    const jwt = res.data?.data?.jwtend || res.data?.data?.token || res.data?.token || res.data?.accessToken
                    if (jwt) {
                        localStorage.setItem('token', String(jwt))
                        localStorage.setItem('authToken', `Bearer ${String(jwt)}`)
                            // 立刻让后续请求携带 Authorization
                            ; (myaxios.defaults.headers.common as any)['Authorization'] = `Bearer ${String(jwt)}`
                    }
                    // 保存用户名与角色名，供主界面显示
                    try {
                        const d: any = res.data?.data || {}
                        const roleFromArray = Array.isArray(d.roles) && d.roles.length ? (d.roles[0]?.roleName || d.roles[0]?.name) : ''
                        const roleName = d.roleName || d.role || d.userRole || roleFromArray || ''
                        if (roleName) localStorage.setItem('userRole', String(roleName))
                        const backendUserName = d.userName || d.userAccount || ''
                        if (backendUserName) localStorage.setItem('username', String(backendUserName))
                        // 保存部门与岗位（兼容不同返回字段名）
                        const organizationName = d.organizationName || d.organization || d.departmentName || d.orgName || ''
                        const positionName = d.positionName || d.position || d.jobTitle || ''
                        if (organizationName) localStorage.setItem('organizationName', String(organizationName))
                        if (positionName) localStorage.setItem('positionName', String(positionName))
                        // 保存账号与手机号
                        const userAccount = d.userAccount || d.account || d.userCode || ''
                        const mobile = d.userPhone || d.mobile || d.phone || d.tel || ''
                        if (userAccount) localStorage.setItem('userAccount', String(userAccount))
                        if (mobile) localStorage.setItem('mobile', String(mobile))
                    } catch { }
                    // 记住账号密码
                    if (rememberMe.value) {
                        localStorage.setItem('rememberMe', '1')
                        localStorage.setItem('rememberUsername', username.value)
                        localStorage.setItem('rememberPassword', password.value)
                    } else {
                        localStorage.setItem('rememberMe', '0')
                        localStorage.removeItem('rememberUsername')
                        localStorage.removeItem('rememberPassword')
                    }
                    router.push({ name: 'home' })
                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
            .catch(err => {
                console.log(err);
            })

    } catch (e) {
        errorMessage.value = '登录失败，请稍后重试'
    } finally {
        isSubmitting.value = false
    }
}
</script>

<style scoped>
.login-page {
    min-height: 100vh;
    display: grid;
    place-items: center;
    background: radial-gradient(1200px 600px at 10% 10%, #eaf2ff 0%, transparent 60%),
        radial-gradient(1000px 500px at 90% 90%, #eefbf3 0%, transparent 60%),
        linear-gradient(120deg, #f6f9ff, #f9fbff);
    padding: 24px;
    position: relative;
    overflow: hidden;
}

.glass-card {
    width: 100%;
    max-width: 420px;
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.6);
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(44, 62, 80, 0.08);
    padding: 28px;
}

.brand {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 18px;
}

.logo-circle {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: linear-gradient(135deg, #3b82f6, #22c55e);
    color: #fff;
    display: grid;
    place-items: center;
    font-weight: 700;
    font-size: 20px;
    box-shadow: 0 8px 20px rgba(34, 197, 94, 0.25);
}

.title-group h1 {
    margin: 0;
    font-size: 20px;
    color: #1f2d5c;
}

.title-group p {
    margin: 2px 0 0 0;
    color: #7483a8;
    font-size: 12px;
}

.form {
    margin-top: 12px;
    display: grid;
    gap: 14px;
}

.field label {
    display: block;
    color: #42507a;
    font-size: 13px;
    margin-bottom: 8px;
}

.input-wrap {
    position: relative;
}

.input-wrap input {
    width: 100%;
    padding: 12px 40px 12px 36px;
    border: 1px solid #d9e1f2;
    border-radius: 10px;
    outline: none;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s, background-color 0.2s;
    background: #fff;
}

.input-wrap input:focus {
    border-color: #5b8def;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}

.prefix {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    color: #7a86a8;
}

.suffix-btn {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 16px;
}

.captcha-row {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 10px;
}

.captcha {
    width: 100px;
    height: 40px;
    border-radius: 10px;
    border: 1px solid #d9e1f2;
    background: #fff;
    display: grid;
    place-items: center;
    cursor: pointer;
}

.error {
    color: #dc2626;
    font-size: 13px;
    margin-top: -4px;
}

.remember {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: #42507a;
    font-size: 13px;
}

.submit {
    margin-top: 4px;
    width: 100%;
    padding: 12px 16px;
    border-radius: 10px;
    border: 0;
    background: linear-gradient(135deg, #3b82f6, #22c55e);
    color: white;
    font-weight: 600;
    letter-spacing: 0.5px;
    cursor: pointer;
    transition: transform 0.05s ease, box-shadow 0.2s ease, opacity 0.2s ease;
    box-shadow: 0 10px 20px rgba(34, 197, 94, 0.25);
}

.submit:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.submit:not(:disabled):active {
    transform: translateY(1px);
}

.footer-note {
    margin-top: 14px;
    text-align: center;
    color: #8b97b8;
    font-size: 12px;
}

.bg-ornament {
    position: absolute;
    filter: blur(60px);
    opacity: 0.6;
    pointer-events: none;
}

.bg-1 {
    width: 320px;
    height: 320px;
    border-radius: 50%;
    background: #c7d2fe;
    left: -80px;
    top: -60px;
}

.bg-2 {
    width: 420px;
    height: 420px;
    border-radius: 50%;
    background: #bbf7d0;
    right: -120px;
    bottom: -120px;
}
</style>
